package com.luo.backend.service;

import com.luo.backend.dto.MerchantResponse;
import com.luo.backend.dto.UpdateMerchantRequest;
import com.luo.backend.entity.Merchant;
import com.luo.backend.repository.MerchantRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 商家信息管理服务
 */
@Service
public class MerchantInfoService {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantInfoService.class);
    
    @Autowired
    private MerchantRepository merchantRepository;
    
    /**
     * 获取商家信息
     */
    public MerchantResponse getMerchantInfo(Long merchantId) {
        logger.info("获取商家信息 - merchantId: {}", merchantId);
        
        Merchant merchant = merchantRepository.findById(merchantId)
            .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        return new MerchantResponse(merchant);
    }
    
    /**
     * 更新商家信息
     */
    @Transactional
    public MerchantResponse updateMerchantInfo(Long merchantId, UpdateMerchantRequest request) {
        logger.info("更新商家信息 - merchantId: {}", merchantId);
        
        Merchant merchant = merchantRepository.findById(merchantId)
            .orElseThrow(() -> new RuntimeException("商家不存在"));
        
        // 更新字段
        if (request.getName() != null && !request.getName().trim().isEmpty()) {
            merchant.setName(request.getName());
        }
        // ⭐ 更新Logo
        if (request.getLogo() != null) {
            merchant.setLogo(request.getLogo().trim().isEmpty() ? null : request.getLogo());
        }
        if (request.getDescription() != null) {
            merchant.setDescription(request.getDescription());
        }
        if (request.getPhone() != null) {
            merchant.setPhone(request.getPhone());
        }
        if (request.getAddress() != null) {
            merchant.setAddress(request.getAddress());
        }
        if (request.getBusinessHours() != null) {
            merchant.setBusinessHours(request.getBusinessHours());
        }
        if (request.getMinOrderAmount() != null) {
            merchant.setMinOrderAmount(request.getMinOrderAmount());
        }
        if (request.getDeliveryFee() != null) {
            merchant.setDeliveryFee(request.getDeliveryFee());
        }
        
        merchant.setUpdatedAt(LocalDateTime.now());
        Merchant savedMerchant = merchantRepository.save(merchant);
        
        logger.info("更新商家信息成功 - merchantId: {}", merchantId);
        return new MerchantResponse(savedMerchant);
    }
}





